package com.example.homemodule.view.ui;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.examination.mlib.baseold.AnswerRecommendDoctorEntity;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.utils.DialogUtils;
import com.example.homemodule.listener.OnAnswerCardListener;
import com.example.homemodule.model.bean.AnswerActivityDetailsEntity;
import com.example.homemodule.model.bean.ProtocalEntity;
import com.example.homemodule.utils.HomeUtils;
import com.examination.mlib.baseold.AnswerDetailsListEntity;
import com.example.homemodule.HomeUrl;
import com.example.homemodule.R;
import com.example.homemodule.adapter.AnswerPagerAdapter;
import com.example.homemodule.view.ui.AnswerCardFragment;
import com.example.homemodule.view.view.NumberTextView.RiseNumberTextView;
import com.google.gson.Gson;
import com.examination.mlib.baseold.AnswerResultEntity;
import com.examination.mlib.baseold.ModuleBaseActivity;
import com.examination.mlib.interfaceapi.NetWorkCallBack;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.oss.UploadOssUtils;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.ListUtil;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.ScreenUtils;
import com.yilijk.base.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import crossoverone.statuslib.StatusUtil;

import static androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;

import static com.examination.mlib.constants.AllStringConstants.getByDocumentNo;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 平台活动 健康答题活动页面
 */
@Route(path = ARouterConstants.HealthAnswerActivity)
public class HealthAnswerActivity extends ModuleBaseActivity {
    private View topView, backView, getIv, ruleIv, getCl;
    private ViewPager viewPager;
    private AnswerPagerAdapter pagerAdapter;
    private List<AnswerDetailsListEntity.DataItem> beans = new ArrayList<>();
    private RiseNumberTextView rmbCountTv;
    private String platformActivitiesId, platformActivitiesSubjectId;
    //未领取红包数
    private int notClaimedRedEnvelop;
    private TextView tv_red_count;
    // 未领红包动效
    private Animation redCountAnim;
    private ImageView myBalanceIv;
    private boolean isLoopAnim = false;
    private Dialog dialogAnswerInfo, dialogWrongAnswer, dialogRedEnvelopes;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //沉浸式设置
        StatusUtil.setSystemStatus(this, true, true);
    }

    @Override
    public int bondLayout() {
        return R.layout.activity_health_answer;
    }

    @Override
    public void initView() {
        platformActivitiesId = getIntent().getStringExtra("platformActivitiesId");
        platformActivitiesSubjectId = getIntent().getStringExtra("platformActivitiesSubjectId");

        redCountAnim = AnimationUtils.loadAnimation(HealthAnswerActivity.this, R.anim.swing_anim);


        topView = findViewById(R.id.view_top);
        int statusH = StatusUtil.getStatusBarHeight(this);
        if (statusH <= 0) {
            statusH = ScreenUtils.dip2px(this, 30);
        }
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) topView.getLayoutParams();
        layoutParams.topMargin = statusH;
        topView.setLayoutParams(layoutParams);

        backView = findViewById(R.id.iv_back);
        viewPager = findViewById(R.id.view_pager);
        rmbCountTv = findViewById(R.id.tv_rmb_count);
        TextPaint paint = rmbCountTv.getPaint();
//                        paint.setStrokeWidth(10f);
        paint.setStrokeWidth(1.5f);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);

        getIv = findViewById(R.id.iv_get);
        getCl = findViewById(R.id.cl_get);
        ruleIv = findViewById(R.id.iv_rule);
        tv_red_count = findViewById(R.id.tv_red_count);
        myBalanceIv = findViewById(R.id.iv_my_balance);


//        beans.add("0");
//        beans.add("1");
//        beans.add("2");
//        beans.add("3");
//        beans.add("4");
//        beans.add("5");
        pagerAdapter = new AnswerPagerAdapter(getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, beans, new OnAnswerCardListener() {
            @Override
            public void checkAnswerInfo(int position) {
                if (dialogAnswerInfo != null) {
                    if (dialogAnswerInfo.isShowing()) {
                        dialogAnswerInfo.dismiss();
                    }
                }
                dialogAnswerInfo = DialogUtils.showAnswerInfoDialog(HealthAnswerActivity.this, beans.get(position));
            }

            @Override
            public void gotoPreDay(int position) {
                if (position != 0) {
                    viewPager.setCurrentItem(position - 1, true);
                }
            }

            @Override
            public void gotoToday(int position) {
                if (viewPager.getCurrentItem() != ListUtil.getSize(beans) - 2) {
                    viewPager.setCurrentItem(ListUtil.getSize(beans) - 2, true);
                }
            }

            @Override
            public void gotoNextDay(int position) {
                if (position < ListUtil.getSize(beans) - 1) {
                    viewPager.setCurrentItem(position + 1, true);
                }
            }

            @Override
            public void checkHistory(int position) {
                Bundle bundle = new Bundle();
                bundle.putString("platformActivitiesId", platformActivitiesId);
                HomeUtils.push(HealthAnswerActivity.this, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.Rumor, bundle);
            }

            @Override
            public void chooseLeftAnswer(int position) {
                AnswerDetailsListEntity.DataItem dataItem = beans.get(position);
                answerResultFilled(dataItem, true);
            }

            @Override
            public void chooseRightAnswer(int position) {
                AnswerDetailsListEntity.DataItem dataItem = beans.get(position);
                answerResultFilled(dataItem, false);

            }
        });
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(3);//预加载3个页面
//        viewPager.setPageMargin(ScreenUtils.dip2px(this,30));
        viewPager.setPageTransformer(false, new AnswerPagerAdapter.LoopTransformer());


    }

    private void answerResultFilled(AnswerDetailsListEntity.DataItem dataItem, boolean answer) {

        RequestParams jsonObject = new RequestParams();
        jsonObject.put("platformActivitiesId", dataItem.getPlatformActivitiesId());
        jsonObject.put("subjectId", dataItem.getPlatformActivitiesSubjectId());
        jsonObject.put("filledOption", answer);
        LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).showLoading();
        HttpUtils.get(HomeUrl.answerResultFilled, jsonObject, new HttpCallBack<AnswerResultEntity>() {
            @Override
            public void onSuccess(AnswerResultEntity entity, int i) {
                if (entity != null) {
                    if ("200".equals(entity.getStatus()) && entity.getData() != null) {
                        Intent intent = new Intent(AllStringConstants.BroadcastRefreshHomeData);
                        sendBroadcast(intent);
                        if (entity.getData().isFilledResult()) {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("platformActivitiesId", entity.getData().getPlatformActivitiesId());
                                jsonObject.put("subjectId", entity.getData().getSubjectId());
                                if (dialogRedEnvelopes != null){
                                    if (dialogRedEnvelopes.isShowing()){
                                        dialogRedEnvelopes.dismiss();
                                    }
                                }
                                dialogRedEnvelopes =  DialogUtils.showRedEnvelopes(HealthAnswerActivity.this, jsonObject, HomeUrl.claimedRedEnvelope, new DialogUtils.RedEnvelopesListener() {
                                    @Override
                                    public void onClose() {
                                        initPageData(true);
                                    }

                                    @Override
                                    public void useRmb(AnswerRecommendDoctorEntity.Data data) {
                                        if (data != null && !TextUtils.isEmpty(data.getDoctorId())) {
                                            //快速购药
                                            Bundle bundle = new Bundle();
                                            bundle.putString("doctorId", data.getDoctorId());
                                            HomeUtils.push(HealthAnswerActivity.this, KitArouterConstants.CART_DOCTORBUNDLE, KitArouterConstants.Cart.Drug, bundle);
                                        } else {
                                            HomeUtils.goHome(HealthAnswerActivity.this);
                                        }
                                    }
                                });
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            if (dialogWrongAnswer != null) {
                                if (dialogWrongAnswer.isShowing()) {
                                    dialogWrongAnswer.dismiss();
                                }
                            }
                            dialogWrongAnswer = DialogUtils.showWrongAnswer(HealthAnswerActivity.this, DialogUtils.ENVELOPES_ANSWER_WRONG, new DialogUtils.WrongAnswerListener() {
                                @Override
                                public void onDismiss() {
                                    initPageData(true);
                                }
                            });
                        }
                    } else {
                        if (!TextUtils.isEmpty(entity.getMessage())) {
                            ToastUtils.showShort(entity.getMessage());
                        }
                    }
                }
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).dismissLoading();
            }
        });
    }

    @Override
    public void initData() {

        initPageData(true);

    }

    private void initPageData(boolean isRefreshAnswerList) {
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("platformActivitiesId", platformActivitiesId);
        jsonObject.put("dateParam", System.currentTimeMillis());
        LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).showLoading();
        HttpUtils.get(HomeUrl.getAnswerActivityDetails, jsonObject, new HttpCallBack<AnswerActivityDetailsEntity>() {
            @Override
            public void onSuccess(AnswerActivityDetailsEntity entity, int i) {
                LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).dismissLoading();
                if (entity.isResult() && entity != null && entity.getData() != null) {
                    AnswerActivityDetailsEntity.Data data = entity.getData();

//                        String textStr = "健康币：" + data.getHealthyCurrencyAmount() + "个";
//                        SpannableString spannableString = new SpannableString(textStr);
//                        StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
//                        AbsoluteSizeSpan absoluteSizeSpan = new AbsoluteSizeSpan(20, true);
//                        AbsoluteSizeSpan absoluteSizeSpan1 = new AbsoluteSizeSpan(12, true);
//                        spannableString.setSpan(styleSpan, 4, textStr.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//                        spannableString.setSpan(absoluteSizeSpan, 4, textStr.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//                        spannableString.setSpan(absoluteSizeSpan1, textStr.length() - 1, textStr.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
//                        rmbCountTv.setText(spannableString);
//                        rmbCountTv.setText(data.getHealthyCurrencyAmount()+"");
                    if (!(data.getHealthyCurrencyAmount() + "").equals(rmbCountTv.getText().toString())) {
                        rmbCountTv.withNumber(data.getHealthyCurrencyAmount()).start();
                    }

                    notClaimedRedEnvelop = data.getNotClaimedRedEnvelop();
                    if (notClaimedRedEnvelop > 0) {
                        tv_red_count.setText(notClaimedRedEnvelop + "");
                        tv_red_count.setVisibility(View.VISIBLE);
                        getIv.setVisibility(View.VISIBLE);

                        isLoopAnim = true;
                        redCountAnim.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {
                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                animation.reset();
                                if (isLoopAnim) {
                                    animation.setAnimationListener(this);
                                    animation.start();
                                }
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {
                            }
                        });
                        getCl.startAnimation(redCountAnim);

                    } else {
                        isLoopAnim = false;
                        tv_red_count.setVisibility(View.INVISIBLE);
                        getIv.setVisibility(View.INVISIBLE);
                    }
                }

                if (isRefreshAnswerList) {
                    getAnswerDetailsList(jsonObject);
                }
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).dismissLoading();
            }
        });

    }

    private void getAnswerDetailsList(RequestParams jsonObject) {

        LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).showLoading();
        HttpUtils.get(HomeUrl.getAnswerDetailsList, jsonObject, new HttpCallBack<AnswerDetailsListEntity>() {
            @Override
            public void onSuccess(AnswerDetailsListEntity entity, int i) {
                LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).dismissLoading();
                if (entity != null && entity.getData() != null && ListUtil.getSize(entity.getData()) > 0) {
                    beans.clear();
                    beans.addAll(entity.getData());
                    beans.add(new AnswerDetailsListEntity.DataItem());
                    pagerAdapter.notifyDataSetChanged();
                    viewPager.setAdapter(pagerAdapter);
                    viewPager.setCurrentItem(ListUtil.getSize(beans) - 2, false);
                }
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).dismissLoading();
            }
        });
    }

    @Override
    public void initEvent() {
        ClickUtils.setFastOnClickListener(backView, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ClickUtils.setFastOnClickListener(getIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                DialogUtils.showRedEnvelopes(HealthAnswerActivity.this);
//                DialogUtils.showRedEnvelopesScreen(HealthAnswerActivity.this);
                if (notClaimedRedEnvelop > 0) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("platformActivitiesId", platformActivitiesId);
                        if (dialogRedEnvelopes != null){
                            if (dialogRedEnvelopes.isShowing()){
                                dialogRedEnvelopes.dismiss();
                            }
                        }
                        dialogRedEnvelopes = DialogUtils.showRedEnvelopes(HealthAnswerActivity.this, jsonObject, HomeUrl.claimedAllRedEnvelope, new DialogUtils.RedEnvelopesListener() {
                            @Override
                            public void onClose() {
                                initPageData(true);
                            }

                            @Override
                            public void useRmb(AnswerRecommendDoctorEntity.Data data) {
                                if (data != null && !TextUtils.isEmpty(data.getDoctorId())) {
                                    //快速购药
                                    Bundle bundle = new Bundle();
                                    bundle.putString("doctorId", data.getDoctorId());
                                    HomeUtils.push(HealthAnswerActivity.this, KitArouterConstants.CART_DOCTORBUNDLE, KitArouterConstants.Cart.Drug, bundle);
                                } else {
                                    HomeUtils.goHome(HealthAnswerActivity.this);
                                }
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        ClickUtils.setFastOnClickListener(ruleIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestParams jsonObject = new RequestParams();
                jsonObject.put("documentNo", "rulesForDailyAnswerActivity");

                LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).showLoading();
                HttpUtils.get(getByDocumentNo, new HttpCallBack<ProtocalEntity>() {
                    @Override
                    public void onSuccess(ProtocalEntity entity, int i) {
                        if (entity.isResult() && entity.getData() != null) {

                            ARouter.getInstance().build(ARouterConstants.MineWebviewActivity)
                                    .withString("title", entity.getData().getTitle())
                                    .withBoolean("ishtml", true)
                                    .withString("url", entity.getData().getContent())
                                    .withBoolean("isShowLoading", true).navigation();
                        }
                    }

                    @Override
                    public void onFailure(String s, int i) {
                        LoadingUtils.getLoadingUtils(HealthAnswerActivity.this).dismissLoading();
                    }
                });
            }
        });
        ClickUtils.setFastOnClickListener(myBalanceIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HomeUtils.push(HealthAnswerActivity.this, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyBalance);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialogAnswerInfo != null) {
            if (dialogAnswerInfo.isShowing()) {
                dialogAnswerInfo.dismiss();
            }
            dialogAnswerInfo = null;
        }
        if (dialogWrongAnswer != null) {
            if (dialogWrongAnswer.isShowing()) {
                dialogWrongAnswer.dismiss();
            }
            dialogWrongAnswer = null;
        }
        if (dialogRedEnvelopes != null){
            if (dialogRedEnvelopes.isShowing()){
                dialogRedEnvelopes.dismiss();
            }
            dialogRedEnvelopes.dismiss();
        }
    }
}
